package controller

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"kf/models/dao"
	"kf/models/entity"
	"kf/utils/R"
	"net/http"
	"strconv"
)

type SysDictController struct {
	SysDictDao *dao.SysDictDao
	Log        *zap.Logger
}

func (sysDictController *SysDictController) GetDictOptions(c *gin.Context) {
	code := c.Param("code")
	options := sysDictController.SysDictDao.ListDictItemsByCode(code)
	c.JSON(http.StatusOK, R.ReturnSuccess(options))
}

func (sysDictController *SysDictController) GetDictPage(context *gin.Context) {
	var pageQuery entity.SysDictPageQuery
	err := context.ShouldBindQuery(&pageQuery)
	if err != nil {
		context.JSON(http.StatusInternalServerError, R.ReturnFailMsg(err.Error()))
		return
	}
	users, err := sysDictController.SysDictDao.GetDictPage(pageQuery)
	if err != nil {
		context.JSON(http.StatusInternalServerError, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(users))
}

func (sysDictController *SysDictController) GetDictForm(context *gin.Context) {
	dictIdStr := context.Param("dictId")
	// 尝试将字符串转换为整数
	dictId, err := strconv.ParseUint(dictIdStr, 10, 64)
	if err != nil {
		// 如果转换失败，返回错误响应
		context.JSON(http.StatusInternalServerError, "Invalid ID")
		return
	}
	form, err := sysDictController.SysDictDao.GetDictForm(dictId)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(form))
}

func (sysDictController *SysDictController) SaveDict(context *gin.Context) {
	var dict entity.DictPageVO
	err := context.ShouldBindJSON(&dict)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	f, err := sysDictController.SysDictDao.SaveDict(dict)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(f))
}

func (sysDictController *SysDictController) DeleteDict(context *gin.Context) {
	dictIds := context.Param("dictIds")
	f, err := sysDictController.SysDictDao.DeleteDict(dictIds)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(f))
}

func (sysDictController *SysDictController) UpdateDict(context *gin.Context) {
	var form entity.DictForm
	err := context.ShouldBindJSON(&form)
	if err != nil {
		sysDictController.Log.Error("绑定失败", zap.Error(err))
		context.JSON(http.StatusInternalServerError, "修改字典信息失败")
		return
	}
	param := context.Param("dictId")
	id, err := strconv.ParseUint(param, 10, 64)
	if err != nil {
		sysDictController.Log.Error("绑定失败", zap.Error(err))
		context.JSON(http.StatusInternalServerError, "修改字典信息失败")
		return
	}
	result, err := sysDictController.SysDictDao.UpdateDict(id, form)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(result))
}
